//
//  FLWallPaperDetailsViewController.m
//  FeeLing
//
//  Created by 乔光玉 on 2019/1/3.
//  Copyright © 2019年 大仙儿飘. All rights reserved.
//
#import <Photos/PhotosTypes.h>
#import "DownLoadVideoService.h"
#import "ZYLivePhotoTool.h"
#import "PHAssetModel.h"
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVTime.h>
#import <Photos/Photos.h>
#import "FLWallPaperDetailsViewController.h"

@interface FLWallPaperDetailsViewController ()
{
    NSInteger flag;
    BOOL _ishidden;
    BOOL _iscontactplay;
    
}
@property(nonatomic,strong)UIButton * backButton;
@property(nonatomic,strong)UIButton * downButton;
@property(nonatomic,strong)UIButton * deskButton;
@property(nonatomic,strong)UIButton * screenButton;
@property(nonatomic,strong)UIImageView * bgImageView;
@property (strong, nonatomic)AVPlayer *myPlayer;//播放器
@property (strong, nonatomic)AVPlayerItem *item;//播放单元
@property (strong, nonatomic)AVPlayerLayer *playerLayer;//播放界面（layer）
@property(nonatomic,strong)UIImageView *screenmageView;
@property(nonatomic,strong)UIImageView *deskImageView;
@end

@implementation FLWallPaperDetailsViewController
-(BOOL)prefersStatusBarHidden{
    
    return YES;
}
-(void)back:(UIButton *)sender{
    [self.myPlayer pause];
    [self.navigationController popViewControllerAnimated:YES];
}





-(void)down:(UIButton *)sender{
    dispatch_async(dispatch_get_main_queue(), ^{
        __weak typeof(self)weakself = self;
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            NSLog(@"status%ld",status);
            
            __strong typeof(weakself) strongself = weakself;
            if (status == PHAuthorizationStatusAuthorized) {
                [strongself clickDownLoad];
                
                
                
            }else {
                
                
                
                
                
            }
            
            
        }];
        
    });
   

    
    
}
-(void)clickDownLoad{
    dispatch_async(dispatch_get_main_queue(), ^{
        __weak typeof(self)weakself = self;
        [MBProgressHUD showMessag:@"Loading" toView:self.view];
        
    });
    
    flag = 1;
    [DownLoadVideoService downloadAudioWithUrl:self.object[@"videoFileUrl"] saveDirectoryPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] fileName:[NSString stringWithFormat:@"%@", self.object.objectId] finish:^(NSString *filePath2) {
        
        AVURLAsset*audioAsset=[[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:filePath2] options:nil];
        CMTime audioDuration=audioAsset.duration;
        float audioDurationSeconds=CMTimeGetSeconds(audioDuration);
        
        AVAsset *asset = [[ZYLivePhotoTool shareTool] cutVideoWithPath:filePath2 startTime:0.0 endTime:audioDurationSeconds];
        
        
        [[ZYLivePhotoTool shareTool] generatorOriginImgWithAsset:asset seconds:2.0 imageName:@"image" handleImg:^(UIImage *originImage, NSString *imagePath, NSError *error) {
            
            NSString *outPut = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, true).firstObject;
            NSString *newImgPath = [outPut stringByAppendingPathComponent:@"IMG.JPG"];
            NSString *newVideoPath = [outPut stringByAppendingPathComponent:@"IMG.MOV"];
            [[NSFileManager defaultManager] removeItemAtPath:newImgPath error:nil];
            [[NSFileManager defaultManager] removeItemAtPath:newVideoPath error:nil];
            
            if (@available(iOS 9.1, *)) {
                [[ZYLivePhotoTool shareTool] generatorLivePhotoWithAsset:asset originImgPath:imagePath livePhotoImgPath:newImgPath livePhotoVideoPath:newVideoPath handleLivePhoto:^(PHLivePhoto *livePhoto) {
                    //                    photoView.livePhoto = livePhoto;
                    if (self->flag == 1) {
                        
                        self->flag = 3;
                        [[ZYLivePhotoTool shareTool] saveLivePhotoWithVideoPath:newVideoPath imagePath:newImgPath handle:^(BOOL success, NSError *error) {
                            if (success) {
                                NSLog(@"aaa");
                                dispatch_sync(dispatch_get_main_queue(), ^{
                                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                                    [MBProgressHUD showError:NSLocalizedString(@"baocunchenggong", nil) toView:self.view];
                                });
                                
                            } else {
                                dispatch_sync(dispatch_get_main_queue(), ^{
                                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                                    [MBProgressHUD showError:NSLocalizedString(@"baocunshibai", nil) toView:self.view];
                                });
                                
                                NSLog(@"bbb");
                            }
                            
                        }];
                        
                    }
                }];
            } else {
                // Fallback on earlier versions
            }
            
            
        }];
        
        
        
        
    } failed:^{
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];
    
    
    
    
    
}
-(void)screenButtonclick:(UIButton *)sender{
    
    _iscontactplay = YES;
    _ishidden = NO;
    [self.myPlayer seekToTime:CMTimeMake(0, 1)];
    [self.myPlayer play];
    
    
    self.screenmageView.hidden = NO;
    self.deskImageView.hidden = YES;
    
    self.backButton.hidden = YES;
    self.downButton.hidden = YES;
    
    self.screenButton.hidden = YES;
    
    self.deskButton.hidden = YES;
    
}
-(void)deskButtonclick:(UIButton *)sender{
    
    _iscontactplay = NO;
    _ishidden = NO;
    [self.myPlayer pause];
    
    self.deskImageView.hidden = NO;
    self.screenmageView.hidden = YES;
    
    self.backButton.hidden = YES;
    self.downButton.hidden = YES;
    
    self.screenButton.hidden = YES;
    
    self.deskButton.hidden = YES;
    
}
-(void)tapclick{
    self.screenmageView.hidden = YES;
    self.deskImageView.hidden = YES;
    _ishidden = YES;
    _iscontactplay = YES;
    
    self.backButton.hidden = NO;
    self.downButton.hidden = NO;
   
    self.screenButton.hidden = NO;
    
    self.deskButton.hidden = NO;
    [self.myPlayer play];
    
}
-(void)moviePlayDidEnd:(AVPlayerItem *)playitem{
    
    [self.myPlayer seekToTime:CMTimeMake(0, 1)];
    [self.myPlayer play];
    _iscontactplay = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
    
    _ishidden = YES;
    self.bgImageView = [[UIImageView alloc]init];
    [self.bgImageView sd_setImageWithURL:[NSURL URLWithString:self.object[@"imageFileUrl"]]];
    self.bgImageView.frame = CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT);
    [self.view addSubview:self.bgImageView];
    
    NSURL *mediaURL = [NSURL URLWithString:self.object[@"videoFileUrl"]];
    self.item = [AVPlayerItem playerItemWithURL:mediaURL];
    self.myPlayer = [AVPlayer playerWithPlayerItem:self.item];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.item];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.myPlayer];
    self.playerLayer.frame = CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT);
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill ;
    [self.view.layer addSublayer:self.playerLayer];
    [self.myPlayer play];
     _iscontactplay = YES;
    self.backButton = [UIButton new];
    [self.backButton setImage:[UIImage imageNamed:@"壁纸返回"] forState:UIControlStateNormal];
    self.backButton.frame = CGRectMake(11, SCREENHEIGHT-27-30, 30, 30);
    [self.backButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backButton];
    
    self.downButton = [UIButton new];
    [self.downButton setImage:[UIImage imageNamed:@"壁纸下载"] forState:UIControlStateNormal];
    self.downButton.frame = CGRectMake(SCREENWIDTH-14-30, SCREENHEIGHT-27-30, 30, 30);
    [self.downButton addTarget:self action:@selector(down:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.downButton];
    
    self.screenButton =[UIButton new];
    
    self.screenButton.frame = CGRectMake(59, SCREENHEIGHT-62,(SCREENWIDTH-59-60-20)/2 , 40);
    self.screenButton.backgroundColor = [UIColor colorWithHexString:@"#F63632"];
    self.screenButton.layer.cornerRadius =20;
    self.screenButton.clipsToBounds = YES;
    self.screenButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 14];
    self.screenButton.titleLabel.numberOfLines = 0;
    [self.screenButton setTitle:NSLocalizedString(@"screensaver", nil) forState:UIControlStateNormal];
    [self.screenButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.screenButton addTarget:self action:@selector(screenButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.screenButton];
    
    
    self.deskButton =[UIButton new];
    
    self.deskButton.frame = CGRectMake(SCREENWIDTH-60-(SCREENWIDTH-59-60-20)/2, SCREENHEIGHT-62,(SCREENWIDTH-59-60-20)/2 , 40);
    self.deskButton.backgroundColor = [UIColor colorWithHexString:@"#FFFFFF"];
    self.deskButton.alpha=0.6;
    self.deskButton.layer.cornerRadius =20;
    self.deskButton.clipsToBounds = YES;
    self.deskButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 14];
    [self.deskButton setTitle:NSLocalizedString(@"desktop", nil) forState:UIControlStateNormal];
    [self.deskButton setTitleColor:[UIColor colorWithHexString:@"#363662"] forState:UIControlStateNormal];
    [self.deskButton addTarget:self action:@selector(deskButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.deskButton];
    
    
    NSArray *appLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString *languageName = [appLanguages objectAtIndex:0];
    self.screenmageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
    self.screenmageView.hidden = YES;
    UITapGestureRecognizer * tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapclick)];
    self.screenmageView.userInteractionEnabled = YES;
    [self.screenmageView addGestureRecognizer:tap];
    [self.view addSubview:self.screenmageView];
    if (SCREENHEIGHT>800) {
        if (![languageName containsString:@"zh"]) {
            [self.screenmageView setImage:[UIImage imageNamed:@"锁屏x英文"]];
            
        }else{
           [self.screenmageView setImage:[UIImage imageNamed:@"锁屏x中文"]];
        }
        
        
    }else{
        if (![languageName containsString:@"zh"]) {
            
           [self.screenmageView setImage:[UIImage imageNamed:@"锁屏英文"]];
            
        }else{
            
          [self.screenmageView setImage:[UIImage imageNamed:@"锁屏中文"]];
            
        }
        
    }
    
    self.deskImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
    self.deskImageView.hidden = YES;
     self.deskImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer * tapp =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapclick)];
    [self.deskImageView addGestureRecognizer:tapp];
    [self.view addSubview:self.deskImageView];
    
    if (SCREENHEIGHT>800) {
        if (![languageName containsString:@"zh"]) {
            [self.deskImageView setImage:[UIImage imageNamed:@"壁纸iphonex 英文"]];
            
        }else{
            [self.deskImageView setImage:[UIImage imageNamed:@"壁纸iphonex 中文"]];
        }
        
        
    }else{
        if (![languageName containsString:@"zh"]) {
            
            [self.deskImageView setImage:[UIImage imageNamed:@"壁纸英文"]];
            
        }else{
            
            [self.deskImageView setImage:[UIImage imageNamed:@"壁纸中文"]];
            
        }
        
    }
    
   
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
